package net.dgg.rz.api.production.controller;

import com.alibaba.fastjson.JSON;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.exception.DggBaseException;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.constant.SystemCommonConstant;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.files.entity.Annex;
import net.dgg.rz.common.files.service.AnnexService;
import net.dgg.rz.common.service.CommonMangerExtService;
import net.dgg.rz.common.service.CommonService;
import net.dgg.rz.common.systemRecord.service.SystemRecordService;
import net.dgg.rz.common.utils.DataPermissionUtils;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.exception.ProductOrderExcption;
import net.dgg.rz.production.service.AllOrderService;
import net.dgg.rz.production.service.FlowNodeService;
import net.dgg.rz.production.service.ProductOrderService;
import net.dgg.tmd.foundation.platform.user.entity.UserDTO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>@Title APP融资生产公用接口controller</p>
 * <p>@Version 2.0.0 版本号</p>
 * <p>@author chenyang</p>
 * <p>@date 2019年04月12日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@RestController
@RequestMapping("/api/rzsc/common")
public class FinanceProductCommonController extends DggBaseController {

    @Autowired
    private AllOrderService allOrderService;
    @Autowired
    private ProductOrderService productOrderService;
    @Autowired
    private FlowNodeService flowNodeService;
    @Autowired
    private CommonMangerExtService zzCommonMangerExtService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    AnnexService annexService;
    @Value("${dgg.oss[0].bucket-uri}")
    private String fastdfsHost;
    @Autowired
    SystemRecordService systemRecordService;
    @Autowired
    DataPermissionUtils dataPermissionUtils;

    /**
     * @return
     * @Description APP 订单备注
     * @Author chenyang
     */
    @RequestMapping("/remark_order")
    public DggRestResponse remarkOrder(Long id, String remark,String userLoginName) {
        try {
            allOrderService.remarkOrder(id, remark, userLoginName);
            return this.getSuccessResponse("success!");
        } catch (CommonExcption e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (ProductOrderExcption e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (RuntimeException e) {
            e.printStackTrace();
            return this.getFailResponse("系统异常，请联系管理员！");
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统异常,请联系管理员!");
        }
    }

    /**
     * @return
     * @Description APP  订单退单
     * @Author chenyang
     */
    @RequestMapping("/return_order")
    public Object returnOrder(@RequestParam Map params) {
        try {
            productOrderService.abandonReasonOrder(JSON.toJSONString(params));
            return this.getSuccessResponse("操作成功!");
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * @return
     * @Author
     * @Description //APP 申请废单
     * @Date
     * @Param
     **/
    @RequestMapping("/nullify_reason_order.do")
    public Object nullifyReasonOrder(@RequestParam Map params) {
        try {
            this.productOrderService.nullifyReasonOrder(JSON.toJSONString(params));
            return this.getSuccessResponse("操作成功!");
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * APP订单转单
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/transfer_order.do", method = RequestMethod.POST)
    public DggRestResponse transferOrder(String orderIds, Long transferUserId, String transferOrderRemark, String userLoginName) {
        try {
            ValidateUtils.strNotEmpty(orderIds, CommonExcption.class, "订单id不能为空");
            ValidateUtils.strNotEmpty(transferUserId, CommonExcption.class, "转单人不能为空");
            Map<String, String> result = productOrderService.transferOrder(orderIds, transferUserId, transferOrderRemark, userLoginName);
            if ("1".equals(result.get("flag"))) {
                return this.getSuccessResponse("转单成功");
            } else {
                return this.getFailResponse(result.get("msg"));
            }
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }


    /**
     * APP 查询字典
     *
     * @return
     */
    @RequestMapping("/tree_book_list")
    public DggRestResponse treeBookList() {
        try {
            return this.getSuccessResponse(zzCommonMangerExtService.queryTreeBookListByCode(ScProductConstant.BUS_YT_DK, 2, 2));
        } catch (DggBaseException e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception ex) {
            ex.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * APP 用户选择信息查询
     *
     * @return
     */
    @RequestMapping(value = "/find_user_choose")
    public DggRestResponse findUserChoose(@RequestParam Map params) {
        try {
            List<UserDTO> userDTOList = commonService.findUserDTOListForApp(params);
            return this.getSuccessResponse(userDTOList);
        }catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * APP 根据业务类型编码查询产品
     *
     * @return
     */
    @RequestMapping(value = "/find_product")
    public DggRestResponse findProduct(String ytCode) {
        try {
            if (StringUtils.isEmpty(ytCode)) {
                return this.getSuccessResponse(new ArrayList<Map>());
            }
            Map map = new HashMap();
            map.put("proType", ytCode);
            map.put("limit", 10000);
            List<Map> products = commonService.searchProduct(map);
            return this.getSuccessResponse(products);
        }catch (DggBaseException e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * @return
     * @Author
     * @Description //APP 根据产品id查询渠道
     * @Date
     * @Param
     **/
    @RequestMapping("/find_channels_by_goodsId")
    public DggRestResponse findChannelsByGoodsId(@RequestParam Long goodsId) {
        try {
            List<Map> channels = commonService.channelByProid(goodsId + "");
            return this.getSuccessResponse(channels);
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * APP 商品属性查询（弃用）
     * @param
     * @return
     */
    @RequestMapping("/product_property.do")
    public DggRestResponse queryProductProperty(String productId) {
        try {
            ValidateUtils.strNotEmpty(productId, ProductOrderExcption.class, "产品id不能为空");
            Map map = new HashMap();
            map.put("proId", productId);
            Map goods = cmsService.productInfo(map);
            return this.getSuccessResponse(goods);
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * APP 暂缓原因
     * @param
     * @return
     */

    @RequestMapping("/suspend_cause")
    public DggRestResponse query_suspend() {
        try {
            List list = commonMangerExtService.queryTreeBookListByCode(ScProductConstant.ZH_YY_CODE, 1, null);
            return this.getSuccessResponse(list);
        } catch (Exception e) {
            throw new ProductOrderExcption(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * 暂缓
     * @param params
     * @return
     */

    @RequestMapping("/suspend_reason_order.do")
    @ResponseBody
    public DggRestResponse suspendReasonOrder(@RequestParam Map params) {
        try {
            String paramStr = JSON.toJSONString(params);
            productOrderService.suspendReasonOrder(paramStr);
            return this.getSuccessResponse("操作成功!");
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }

    /**
     * APP 查询废单、暂缓、退单原因及业务
     * @return
     */
    @RequestMapping("/query_cause_service")
    public DggRestResponse queryCauseOrService(String code) {
        try {
            ValidateUtils.strNotEmpty(code,ProductOrderExcption.class,"状态码不能为空！");
            if (ScProductConstant.BUS_YT_DK.equals(code)) { //查询业务
                return this.getSuccessResponse(zzCommonMangerExtService.queryTreeBookListByCode(code,2,2));
            }else if (ScProductConstant.ZH_YY_CODE.equals(code) || ScProductConstant.FD_YY_CODE.equals(code) || ScProductConstant.TD_YY_CODE.equals(code)) { //查询暂缓、废单或者退单原因
                return this.getSuccessResponse(zzCommonMangerExtService.queryTreeBookListByCode(code,1,null));
            }
            return this.getFailResponse("请输入正确的状态码！");
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * @Author Quanlin Wan
     * @Description //TODO APP上传接口，优化部分代码
     * @Date 16:46 2019/4/23
     * @Param
     * @return
     **/

    @RequestMapping("/upload.do")
    public DggRestResponse uploadFile(@RequestParam String scProductOrderId, @RequestParam MultipartFile file,@RequestParam(required = false) String userLoginName) {
        try {
            Annex item = commonService.uploadFile(scProductOrderId, file, userLoginName);
            return super.getSuccessResponse(item);
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }

    }

    /**
     * @Author Quanlin Wan
     * @Description //TODO APP接收老数据兼容接口（点击接收时调用）
     * @Date 14:05 2019/4/24
     * @Param
     * @return
     **/
    @RequestMapping("/verify_old_receive.do")
    public DggRestResponse uploadFile(@RequestParam String scProductOrderId, @RequestParam(required = false) String userLoginName) {
        try {
            Map map = productOrderService.appAccecpt(scProductOrderId, userLoginName);
            return super.getSuccessResponse(map);
        } catch (DggBaseException e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }

    }


   /**
    * @Author Quanlin Wan
    * @Description //TODO 计算还款时间
    * @Date 13:50 2019/5/10
    * @Param 
    * @return 
    **/
   
    @RequestMapping("/getWorkDays.do")
    @ResponseBody
    public DggRestResponse getWorkDays(@RequestParam Map map) {
        try {
            return this.getSuccessResponse(flowNodeService.getWorkDays(map));
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(ScProductConstant.SYS_ERROR);
        }
    }



}
